// pages/mapListPage/mapListPage.js
import {
  request
} from '../../request/index.js';
import {
  rightJudge
} from '../../lib/right.js';
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 地图数据
    mapList: [],
    // 图层-点数据
    layerList: [],
    // 控制详情页开关
    showModalStatus: false,
    // 详情页动画
    animationData: '',
    // 标记是编辑地图还是添加地图
    flag: '',
    // 当前权限
    right: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (app.globalData.mapGlobal) {
      app.globalData.mapGlobal.map((value, i) => {
        value.createdAt = new Date(value.createdAt).toLocaleDateString()
        if (value._id == app.globalData.activeMapIdGlobal) {
          value.isActive = true
        } else {
          value.isActive = false
        }
      })
      // console.log(app.globalData.mapGlobal)
      // console.log(app.globalData.activeMapIdGlobal)
      this.setData({
        mapList: app.globalData.mapGlobal
      })
    } else {
      console.log('当前无地图！')
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.hideModal()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: async function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: async function () {
    // 如果用户已登录就设置数据
    if (app.globalData.userInfo) {
      // 重新设置全局数据
      app.globalData.mapGlobal = this.data.mapList
      // 修改默认地图
      console.log('当前激活的地图为：', app.globalData.activeMapIdGlobal)
      let tmpModi = {}
      tmpModi['userId'] = app.globalData.userIdGlobal
      tmpModi['teamId'] = app.globalData.defaultTeamId
      tmpModi['mapId'] = app.globalData.activeMapIdGlobal
      if (tmpModi['mapId']) {
        let res2 = await request({
          url: '/teamuser/updateTeamDefaultMap',
          method: 'PUT',
          data: tmpModi
        })
      } else {
        console.log('当前无需更新激活地图')
      }
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  // 点击三个点
  handleMapListTap: function (e) {
    // 设置选中图层
    this.setData({
      selectedMapName: e.currentTarget.dataset.mapname,
      selectedMapId: e.currentTarget.dataset.mapid
    })
    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
      showModalStatus: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 200)
  },
  //隐藏对话框
  hideModal: function () {
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        showModalStatus: false
      })
    }.bind(this), 200)
  },
  // 切换激活
  handleMapActive: async function (e) {
    let selectedActiveMapName = ''
    let selectedActiveMapId = ''
    this.data.mapList.map((value, index) => {
      value.isActive = false;
      if (value.mapName == e.currentTarget.dataset.mapname) {
        value.isActive = !value.isActive
        // 记录此时被激活的地图名称
        selectedActiveMapName = value.mapName
        selectedActiveMapId = value._id
      }
    })
    this.setData({
      mapList: this.data.mapList
    })
    wx.showLoading({
      title: '加载中',
      mask: true
    });
    // 重新获得图层-点数据
    let res = await request({
      url: '/marker/testZty/' + e.currentTarget.dataset.mapid
    }, false)
    // 获取点数据
    let userSetting = await request({
      url: '/setting/getSettingById/' + app.globalData.userIdGlobal
    }, false)
    res.data.data.forEach(v => {
      for (let setting of userSetting.data.data) {
        if (setting.layerId == v._id) {
          v.isVisible = setting.isVisible
        }
      }
    })
    this.setData({
      layerList: res.data.data
    })
    // 修改全局数据
    app.globalData.layerGlobal = this.data.layerList
    app.globalData.activeMapIdGlobal = selectedActiveMapId
    console.log('当前激活地图为：',app.globalData.activeMapIdGlobal)
    /*let resLayer = await request({
      url: '/marker/testZty/' + app.globalData.activeMapIdGlobal,
    },false)
    */
    wx.hideLoading();
    //app.globalData.layerGlobal = resLayer.data.data
  },
  // 添加地图
  addMap: function () {
    // 首先判断是否登录
    if (app.globalData.userInfo == null) {
      wx.showModal({
        title: '提示',
        content: '您还未登录，是否跳转登录？',
        success: res => {
          if (res.confirm) {
            wx.switchTab({
              url: '/pages/myPage/myPage',
            })
          }
        }
      })
    } else {
      // 权限判断
      if (app.globalData.teamUserRight != 2) {
        wx.showModal({
          title: '提示',
          content: '您还没有编辑权限！请联系管理员'
        })
      } else {
        this.setData({
          flag: 'add'
        })
        this.setData({
          showModal2: true
        })
        this.hideModal()
      }
    }
  },
  close_mask2: function () {
    this.setData({
      showModal2: false
    })
  },
  // 输入字段
  inputNewMap: function (e) {
    this.setData({
      modifyMapName: e.detail.value
    })
  },
  async handleAddMapConfirm() {
    if (this.data.flag == 'add') {
      wx.showLoading({
        title: '加载中',
        mask: true
      });
      let addMapDto = {}
      addMapDto['mapName'] = this.data.modifyMapName
      addMapDto['isActive'] = false
      addMapDto['layerCount'] = 0
      addMapDto['team_Id'] = app.globalData.defaultTeamId
      let res = await request({
        url: '/map',
        method: 'POST',
        data: addMapDto
      }, false)
      // 重新获取团队下的地图
      let res2 = await request({
        url: '/map/getMapListByTeamId/' + app.globalData.defaultTeamId
      }, false)
      this.close_mask2()
      res2.data.data.map((value, index) => {
        value.createdAt = new Date(value.createdAt).toLocaleDateString()
        if (value._id == app.globalData.activeMapIdGlobal) {
          value.isActive = true
        }
      })
      app.globalData.mapGlobal = res2.data.data
      this.setData({
        mapList: res2.data.data
      })
      wx.hideLoading()
      // 弹窗
      wx.showToast({
        title: '添加成功！',
        icon: 'success'
      })
    } else if (this.data.flag == 'edit') {
      wx.showLoading({
        title: '加载中',
        mask: true
      });
      let editMapDto = {}
      editMapDto['mapName'] = this.data.modifyMapName
      editMapDto['team_Id'] = app.globalData.defaultTeamId
      let res = await request({
        url: '/map/modify?mapId=' + this.data.selectedMapId,
        method: 'PUT',
        data: editMapDto,
      }, false)
      // 重新获取团队下的地图
      let res2 = await request({
        url: '/map/getMapListByTeamId/' + app.globalData.defaultTeamId
      }, false)
      this.close_mask2()
      res2.data.data.map((value, index) => {
        value.createdAt = new Date(value.createdAt).toLocaleDateString()
        if (value._id == app.globalData.activeMapIdGlobal) {
          value.isActive = true
        }
      })
      app.globalData.mapGlobal = res2.data.data
      this.setData({
        mapList: res2.data.data
      })
      wx.hideLoading()
      wx.showToast({
        title: '修改成功！',
        icon: 'success'
      })
    }
  },
  // 编辑
  editMap() {
    // 判断权限
    if (app.globalData.teamUserRight != 2) {
      wx.showModal({
        title: '提示',
        content: '您还没有编辑权限！请联系管理员'
      })
    } else {
      this.setData({
        flag: 'edit'
      })
      this.setData({
        showModal2: true
      })
      this.hideModal()
    }
  },
  // 删除
  async deleteMap() {
    // 判断权限
    if (app.globalData.teamUserRight != 2) {
      wx.showModal({
        title: '提示',
        content: '您还没有编辑权限！请联系管理员'
      })
    } else {
      let userChoice = await wx.showModal({
        title: '提示',
        content: '确认要删除该地图?请谨慎操作'
      })
      if (userChoice.confirm) {
        await request({
          url: '/map/deleteMap/' + this.data.selectedMapId,
          method: 'DELETE'
        })
        // 重新获取数据
        let res = await request({
          url: '/map/getMapListByTeamId/' + app.globalData.defaultTeamId
        })
        if (res.data.data) {
          res.data.data.map(value => {
            value.createdAt = new Date(value.createdAt).toLocaleDateString()
          })
        }
        this.setData({
          mapList: res.data.data
        })
      } else {

      }
    }
  }
})